package heman.server.controllers;

import java.util.ArrayList;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import heman.server.entities.Table;
import heman.server.entities.TableManager;
import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.server.interfaces.IProcessServerMessage;

/**
 * TableChatController handles TABLECHAT message.
 * <xs:element name="tableChat">
 * 	<xs:complexType>
 * 		<xs:sequence>
 * 		<xs:element ref="text" /> 
 * 		</xs:sequence>
 * 		<xs:attribute name="table" type="table-id" use="required" /> 
 * 	</xs:complexType>
 * </xs:element>
 *
 * @author Yanyi Zhang
 *
 */
public class TableChatController implements IProcessServerMessage {
	public boolean process(Communicator com, Message m) {
		String originator = m.getOriginator();
		NamedNodeMap map = m.contents().getAttributes();
		Node child = m.contents().getChildNodes().item(0);
		String text = null;
		if(child.getNodeName().equals("text"))
			text = child.getTextContent();
		else
			return false;
		String tableID=map.
        		getNamedItem("table").getNodeValue();
		Table TargetTable=TableManager.getInstance().getTable(tableID);
		ArrayList<String> targets = TargetTable.getPlayerIDs();
		//constructing message
		StringBuilder sb = new StringBuilder(Message.responseHeader(true));
		sb.append("<tableChatResponse table=\""+tableID+"\" player=\""+originator+"\">");
		sb.append("<text>"+text+"</text>");
		sb.append("</tableChatResponse>");
		sb.append("</response>");
		Document d = Message.construct(sb.toString());
		Message r = new Message (d);
        r.setOriginator(originator);
		for(String p:targets){
			if(!p.equals(originator)) {
				r.setRecipient(p);
				//System.out.println(p);
				com.distribute(r);
			}
		}
		return true;
	}
}
